package hos.okgo.converter;

import java.io.IOException;
import java.lang.reflect.Type;

import hos.okhttp.utils.OkHttpResponseUtils;
import okhttp3.Response;

/**
 * <p>Title: JsonConvert </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @version : 1.0
 * @date : 2023-02-16 22:51
 */
public abstract class OkGoResponseJsonConverter<T> extends OkGoResponseConverter<T> {

    protected final String success;
    protected final String code;
    protected final String message;

    public OkGoResponseJsonConverter(Type type, String success, String code, String message) {
        super(type);
        this.success = success;
        this.code = code;
        this.message = message;
    }

    public OkGoResponseJsonConverter(Type type, String success, String code) {
        this(type, success, code, "msg");
    }

    public OkGoResponseJsonConverter(Type type) {
        this(type, "0", "code", "msg");
    }

    public OkGoResponseJsonConverter(String success, String code, String message) {
        super();
        this.success = success;
        this.code = code;
        this.message = message;
    }

    public OkGoResponseJsonConverter(String success, String code) {
        this(success, code, "msg");
    }

    public OkGoResponseJsonConverter() {
        this("0", "code", "msg");
    }


    @Override
    public T parseJson(Type succeed, Response response) throws IOException {
        String json = OkHttpResponseUtils.requireJson(response, code, message, success);
        return parseBody(succeed, response, json);
    }

    /**
     * 反序列化JSON
     *
     * @param succeed JSON对象的类型
     * @receiver 原始字符串
     */
    public abstract T parseBody(Type succeed, Response response, String json) throws IOException;
}
